<style lang="less">
  .ivu-poptip-rel{
    width: 100%;
  }
</style>
<template>
  <div class="tem-div">
    <!--搜索-->
    <Card class="tem-card">
      <div class="search-item" :style="searchItemStyle">
        <Form ref="searchForm" label-position="right" inline :label-width="60" class="frm-search">
          <FormItem label="组织名称">
            <i-input placeholder="组织名称" v-model="searchData.name"></i-input>
          </FormItem>
          <FormItem label="机构编码">
            <i-input placeholder="机构编码" v-model="searchData.code"></i-input>
          </FormItem>
          <FormItem label="联系人">
            <i-input placeholder="联系人" v-model="searchData.linkman"></i-input>
          </FormItem>
          <FormItem label="手机号">
            <i-input placeholder="手机号" v-model="searchData.phone"></i-input>
          </FormItem>
        </Form>
      </div>
      <div class="search-btn">
        <hy-icon-btn @click="changeSearchDiv" :text="searchDiv?'收起更多':'展开更多'" :iconType="searchDiv?'chevron-up':'chevron-down'" iconSize="12"></hy-icon-btn>
        <Button type="primary" @click="search(1)" icon="search" :loading="searchListLoading">搜索</Button>
        <i class="search-i"></i>
        <Button class="search-btn-plus" type="ghost" v-btnAuth="{code: 'userAdd'}" icon="plus" @click="showModal('add')">新增</Button>
      </div>
    </Card>
    <!--按钮-->
    <!--<Card class="tem-card">
      <div style="text-align: left">
        <i-button v-btnAuth="{code: 'orgAdd'}" @click="showModal('add')">新增</i-button>
        <i-button @click="showModal('modify','get')">编辑</i-button>
        <i-button @click="showModal('delete')">删除</i-button>
      </div>
    </Card>-->
    <!--表格-->
    <Card class="tem-card">
      <!--table部分-->
      <Table border :columns="columnsTitle" :loading="searchListLoading" :data="list" @on-selection-change="handleSelectionChange"></Table>
      <br>
      <!-- 分页 -->
      <Page :total="totalElement"
            :current="searchData.pageNum"
            size="small"
            show-elevator
            show-sizer
            show-total
            style="text-align: right;"
            @on-change="search"
            @on-page-size-change="pageSizeChange"
            :page-size-opts="pageSizeOpts"
      ></Page>
    </Card>
    <!--弹出框-->
    <Modal v-model="modalObj.addOrModify" :mask-closable="false">
      <p slot="header">
        <span>{{modalObj.title}}</span>
      </p>
      <div style="text-align:center">
        <Form ref="form" :model="modalFormData" :rules="ruleValidate" :label-width="80">
          <FormItem label="上级机构" prop="parentName">
            <Poptip placement="bottom" v-model="showPoptip" style="width: 100%;">
              <Input ref="pId" v-model="modalFormData.parentName" @on-focus="handlerFocus" placeholder="请选择上级机构"></Input>
              <div class="api" ref="tree" slot="content" style="text-align: left;">
                <Tree :data="orgTree" @on-select-change="handleSelectTree"></Tree>
              </div>
            </Poptip>
          </FormItem>
          <hy-form-item :form="modalFormData" :formRow="modalFormItem"></hy-form-item>
        </Form>
      </div>
      <div slot="footer">
        <i-button type="success" size="large" :loading="actionLoading" @click="addOrUp('form')">确定</i-button>
        <i-button size="large" @click="modalObj.addOrModify = false">取消</i-button>
      </div>
    </Modal>
  </div>


</template>
<script>
  import fetch from './service';
  import list from '@/js/mixins/list';
  import HyFormItem from '@/components/common/formItem/formItem.vue';
  import HyDetail from '@/components/common/detail/detail.vue';

  export default {
    components: {
      HyDetail,
      HyFormItem
    },
    mixins: [list],
    data () {
      return {
        loading: false,
        // 查询条件
        searchObj: {},
        modalObj: {
          title: '',
          addOrModify: false
        },
        showPoptip: false,
        columnsTitle: [
          {
            key: 'name',
            title: '机构名称',
            width: 120
          },
          {
            key: 'code',
            title: '机构编码'
          },
          {
            key: 'linkman',
            title: '联系人'
          },
          {
            key: 'phone',
            title: '手机号'
          },
          {
            title: '操作',
            key: 'action',
            width: 180,
            fixed: 'right',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                this._hyTool.createIconBtn(h, params, this.editItem, '编辑', 'edit', 20, {color: '#2db7f5'}, 'orgEdit'),
                this._hyTool.createIconBtn(h, params, this.deleteItem, '删除', 'trash-a', 20, {color: 'red'}, 'orgDelete')
              ]);
            }
          }
        ],
        modalFormData: {
          parentId: '',
          parentName: '',
          code: '',
          weight: '',
          linkman: '',
          phone: '',
          address: '',
          remarks: ''
        },
        modalFormItem: [
          {
            key: 'name',
            title: '机构名称'
          },
          {
            key: 'code',
            title: '机构编码'
          },
          {
            key: 'weight',
            title: '权重'
          },
          {
            key: 'linkman',
            title: '联系人'
          },
          {
            key: 'phone',
            title: '手机号'
          },
          {
            key: 'address',
            title: '地址',
            type: 'textarea'
          },
          {
            key: 'remarks',
            title: '备注',
            type: 'textarea'
          }
        ],
        ruleValidate: {
          parentName: [
            {required: true, message: '上级机构不能为空', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '机构名称不能为空', trigger: 'blur'},
            {max: 20, message: '机构名称不能超过20个字符且不包含空格', trigger: 'blur'}
          ],
          code: [
            {required: true, message: '机构编码不能为空', trigger: 'blur'},
            {max: 20, message: '机构编码不能超过20个字符且不包含空格', trigger: 'blur'}
          ],
          linkman: [
            {required: true, message: '联系人不能为空', trigger: 'blur'},
            {max: 20, message: '联系人不能超过20个字符且不包含空格', trigger: 'blur'}
          ],
          address: [
            {required: true, message: '地址不能为空', trigger: 'blur'},
            {max: 100, message: '地址不能超过100个字符且不包含空格', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '手机号不能为空', trigger: 'blur'},
            {pattern: '^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\\d{8}$', message: '手机号格式不正确', trigger: 'blur'}
          ],
          remarks: [
            {max: 200, message: '备注不能超过200个字符且不包含空格', trigger: 'blur'}
          ]
        },
        orgTree: []
      };
    },
    created () {
      // 初始化加载机构树
      this.getOrgTree();
    },
    methods: {
      _getList () {
        // 作用合并搜索条件
        fetch.getList(Object.assign(this.searchData, this.searchObj)).then(this.callback);
      },
      getOrgTree () {
        let opt = {id: 1};
        fetch.getTree(opt).then((result) => {
          // 展开父级节点
          this.$set(result.data, 'expand', true);
          this.orgTree = [];
          this.orgTree.push(result.data);
        });
      },
      clearFormValid () {
        this.$refs.form.resetFields();
        this.getOrgTree();
      },
      addOrUp (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this._hyTool.cal(true);
            try {
              if (this.modalObj.title === '新增') {
                fetch.saveApi(this.modalFormData).then((data) => {
                  this.$Notice.success({
                    title: '新增成功'
                  });
                  this.search();
                  this.getOrgTree();
                });
              } else {
                let opt = {id: this.modalFormData.id};
                fetch.updateApi(opt, this.modalFormData).then((data) => {
                  this.$Notice.success({
                    title: '修改成功'
                  });
                  this.search();
                });
              }
            } catch (e) {}

            this.modalObj.addOrModify = false;
            this._hyTool.cal(false);
          }
        });
      },
      deleteItem (row) {
        this.$Modal.confirm({
          title: '提示',
          content: '是否删除机构：' + row.name,
          onOk: () => {
            let payload = {id: row.id};
            fetch.deleteApi(payload).then((data) => {
              this.$Notice.success({title: '删除成功'});
              this.search();
            });
          }
        });
      },
      editItem (row) {
        this.modalObj.title = '编辑';
        this.modalObj.addOrModify = true;
        this.clearFormValid();
        fetch.getOne({id: row.id}).then((result) => {
          this.modalFormData = result.data;
        });
      },
      handlerFocus () {
        // 获取父级节点文本框宽度
        let inputWidth = this.$refs.pId.$el.offsetWidth;
        // 设置气泡树div宽度
        this.$refs.tree.style.width = inputWidth - 32 + 'px';
      },
      handleSelectTree (node) {
        this.modalFormData.parentName = node[0].title;
        this.modalFormData.parentId = node[0].id;
        this.$refs.form.validateField('parentName');
        // 验证
        this.showPoptip = false;
      }
    }
  };
</script>
<style scoped>
</style>
